import { StorageData, PlayerStatus, Message } from '../types/autoplayer';

document.addEventListener('DOMContentLoaded', () => {
  const videoSelectorInput = document.getElementById('video-selector') as HTMLInputElement;
  const buttonSelectorInput = document.getElementById('button-selector') as HTMLInputElement;
  const intervalSecInput = document.getElementById('interval-sec') as HTMLInputElement;
  const startBtn = document.getElementById('start-btn') as HTMLButtonElement;
  const stopBtn = document.getElementById('stop-btn') as HTMLButtonElement;
  const resetBtn = document.getElementById('reset-btn') as HTMLButtonElement;
  const statusIndicator = document.getElementById('status-indicator') as HTMLDivElement;
  const countdownLabel = document.getElementById('countdown-label') as HTMLDivElement;
  const logsLink = document.getElementById('logs-link') as HTMLAnchorElement;

  let countdownInterval: number | null = null;

  const updateStatus = (status: PlayerStatus, message?: string) => {
    statusIndicator.className = `status-${status}`;
    statusIndicator.textContent = `● ${status.charAt(0).toUpperCase() + status.slice(1)}`;
    if (message) {
      countdownLabel.textContent = message;
    }
  };

  const saveSettings = () => {
    const settings: StorageData = {
      videoSelector: videoSelectorInput.value,
      buttonSelector: buttonSelectorInput.value,
      intervalSec: parseInt(intervalSecInput.value, 10),
    };
    chrome.storage.sync.set({ settings });
  };

  const loadSettings = () => {
    chrome.storage.sync.get('settings', (data) => {
      if (data.settings) {
        videoSelectorInput.value = data.settings.videoSelector || '';
        buttonSelectorInput.value = data.settings.buttonSelector || '';
        intervalSecInput.value = data.settings.intervalSec || '120';
      }
    });
    chrome.storage.local.get('playerStatus', ({ playerStatus }) => {
        if (playerStatus === 'running') {
            updateStatus('running');
            startCountdown(parseInt(intervalSecInput.value, 10));
        } else {
            updateStatus('idle');
        }
    });
  };

  const startCountdown = (seconds: number) => {
    if (countdownInterval) clearInterval(countdownInterval);
    let remaining = seconds;
    countdownLabel.textContent = `Next check in ${remaining}s`;
    countdownInterval = window.setInterval(() => {
      remaining--;
      if (remaining <= 0) {
        remaining = seconds; // Reset for next cycle
      }
      countdownLabel.textContent = `Next check in ${remaining}s`;
    }, 1000);
  };

  const stopCountdown = () => {
    if (countdownInterval) {
      clearInterval(countdownInterval);
      countdownInterval = null;
    }
    countdownLabel.textContent = '';
  };

  startBtn.addEventListener('click', async () => {
    if (!buttonSelectorInput.value) {
      alert('Button selector is required.');
      return;
    }
    saveSettings();
    const settings: StorageData = {
        videoSelector: videoSelectorInput.value,
        buttonSelector: buttonSelectorInput.value,
        intervalSec: parseInt(intervalSecInput.value, 10),
    };

    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tab && tab.id) {
            await chrome.runtime.sendMessage({ type: 'start', payload: settings });
            await chrome.tabs.sendMessage(tab.id, { type: 'start', payload: settings });
            updateStatus('running');
            startCountdown(settings.intervalSec);
            chrome.storage.local.set({ playerStatus: 'running' });
        }
    } catch (e) {
        updateStatus('error', 'Failed to start');
        console.error(e);
    }
  });

  stopBtn.addEventListener('click', async () => {
    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tab && tab.id) {
            await chrome.runtime.sendMessage({ type: 'stop' });
            await chrome.tabs.sendMessage(tab.id, { type: 'stop' });
            updateStatus('idle');
            stopCountdown();
            chrome.storage.local.set({ playerStatus: 'idle' });
        }
    } catch (e) {
        updateStatus('error', 'Failed to stop');
        console.error(e);
    }
  });

  resetBtn.addEventListener('click', () => {
    stopBtn.click(); // Stop everything first
    videoSelectorInput.value = '';
    buttonSelectorInput.value = '';
    intervalSecInput.value = '120';
    chrome.storage.sync.remove('settings');
    updateStatus('idle');
  });

  logsLink.addEventListener('click', (e) => {
    e.preventDefault();
    chrome.tabs.create({ url: 'logs.html' });
  });

  [videoSelectorInput, buttonSelectorInput, intervalSecInput].forEach(input => {
    input.addEventListener('change', saveSettings);
  });

  chrome.runtime.onMessage.addListener((message: Message) => {
      if (message.type === 'error') {
          updateStatus('error', message.payload.error.message);
          stopCountdown();
          chrome.storage.local.set({ playerStatus: 'error' });
      }
  });

  loadSettings();
});